<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use think\Exception;

class ActiveReport extends Frontend
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->view->assign('title', '主动报工系统');
    }

    /**
     * 主动报工页面
     */
    public function index()
    {
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }

        $workerId = $this->auth->id;
        $error = '';
        $success = '';

        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            try {
                Db::startTrans();
                
                // 验证数据
                $orderId = intval($params['order_id']);
                $modelProcess = $params['model_process']; // 格式：model_id:process_id
                $quantity = intval($params['quantity']);
                $workDate = $params['work_date'];
                $startTime = $params['start_time'];
                $endTime = $params['end_time'];
                $remark = $params['remark'] ?? '';
                
                // 解析型号和工序ID
                $modelProcessArray = explode(':', $modelProcess);
                $modelId = $modelProcessArray[0];
                $processId = $modelProcessArray[1];
                
                // 验证订单和型号
                $order = Db::name('scanwork_order')->where('id', $orderId)->find();
                if (!$order) {
                    throw new Exception('订单不存在');
                }
                
                $orderModel = Db::name('scanwork_order_model')
                    ->where('order_id', $orderId)
                    ->where('model_id', $modelId)
                    ->find();
                if (!$orderModel) {
                    throw new Exception('该订单下没有此产品型号');
                }
                
                // 计算工作时长
                $workHours = 0;
                if (!empty($startTime) && !empty($endTime)) {
                    $start = strtotime($workDate . ' ' . $startTime);
                    $end = strtotime($workDate . ' ' . $endTime);
                    if ($start && $end && $end > $start) {
                        $workHours = round(($end - $start) / 3600, 2);
                    } else {
                        throw new Exception('开始时间必须早于结束时间');
                    }
                }
                
                // 获取选中工序的工价信息
                $processPrice = Db::name('scanwork_process_price')
                    ->where('model_id', $modelId)
                    ->where('process_id', $processId)
                    ->find();
                
                if (!$processPrice) {
                    throw new Exception('该产品型号和工序的工价未设置');
                }
                
                // 计算工资
                $pieceWage = $quantity * $processPrice['price'];
                $timeWage = $workHours * $processPrice['time_price'];
                $totalWage = $pieceWage + $timeWage;
                
                // 创建主动报工记录
                $activeReportId = Db::name('scanwork_active_report')->insertGetId([
                    'order_id' => $orderId,
                    'product_id' => $params['product_id'],
                    'model_id' => $modelId,
                    'process_id' => $processId,
                    'user_id' => $workerId,
                    'quantity' => $quantity,
                    'work_hours' => $workHours,
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'piece_wage' => $pieceWage,
                    'time_wage' => $timeWage,
                    'total_wage' => $totalWage,
                    'work_date' => $workDate,
                    'remark' => $remark,
                    'status' => 0, // 待审核
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                
                // 处理图片上传
                trace('=== 图片上传调试 ===', 'debug');
                trace('$_FILES内容: ' . json_encode($_FILES, JSON_UNESCAPED_UNICODE), 'debug');
                
                if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
                    trace('检测到图片上传', 'debug');
                    $uploadDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'active_report' . DS . date('Ymd') . DS;
                    trace('上传目录: ' . $uploadDir, 'debug');
                    
                    if (!is_dir($uploadDir)) {
                        trace('创建上传目录', 'debug');
                        mkdir($uploadDir, 0755, true);
                    }
                    
                    $count = 0;
                    foreach ($_FILES['images']['tmp_name'] as $k => $tmp) {
                        trace('处理第' . ($k+1) . '个文件', 'debug');
                        trace('文件名: ' . $_FILES['images']['name'][$k], 'debug');
                        trace('临时文件: ' . $tmp, 'debug');
                        trace('错误码: ' . $_FILES['images']['error'][$k], 'debug');
                        trace('文件大小: ' . $_FILES['images']['size'][$k], 'debug');
                        
                        if ($_FILES['images']['error'][$k] == 0) {
                            $ext = strtolower(pathinfo($_FILES['images']['name'][$k], PATHINFO_EXTENSION));
                            $allowExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'jfif'];
                            
                            trace('文件扩展名: ' . $ext, 'debug');
                            trace('是否允许的扩展名: ' . (in_array($ext, $allowExt) ? '是' : '否'), 'debug');
                            
                            if (!in_array($ext, $allowExt)) {
                                trace('文件扩展名不允许，跳过', 'debug');
                                continue;
                            }
                            if ($_FILES['images']['size'][$k] > 10*1024*1024) {
                                trace('文件大小超过限制，跳过', 'debug');
                                continue;
                            }
                            if ($count >= 9) {
                                trace('已达到最大文件数量限制', 'debug');
                                break;
                            }
                            
                            $filename = uniqid() . '.' . $ext;
                            $filepath = $uploadDir . $filename;
                            trace('目标文件路径: ' . $filepath, 'debug');
                            
                            $moveResult = move_uploaded_file($tmp, $filepath);
                            trace('文件移动结果: ' . ($moveResult ? '成功' : '失败'), 'debug');
                            
                            if ($moveResult) {
                                $imageUrl = '/uploads/active_report/' . date('Ymd') . '/' . $filename;
                                trace('图片URL: ' . $imageUrl, 'debug');
                                
                                $insertResult = Db::name('scanwork_active_report_image')->insert([
                                    'active_report_id' => $activeReportId,
                                    'image_url' => $imageUrl,
                                    'image_type' => 1, // 员工上传的图片
                                    'createtime' => time()
                                ]);
                                trace('数据库插入结果: ' . $insertResult, 'debug');
                                $count++;
                            }
                        } else {
                            trace('文件上传错误: ' . $_FILES['images']['error'][$k], 'error');
                        }
                    }
                    trace('总共处理了 ' . $count . ' 个文件', 'debug');
                } else {
                    trace('没有检测到图片上传', 'debug');
                }
                
                Db::commit();
                
                // 如果是AJAX请求，返回JSON响应
                if ($this->request->isAjax()) {
                    return json(['code' => 1, 'msg' => '主动报工提交成功，等待审核']);
                }
                
                $success = '主动报工提交成功，等待审核';
                
            } catch (Exception $e) {
                Db::rollback();
                
                // 如果是AJAX请求，返回JSON响应
                if ($this->request->isAjax()) {
                    return json(['code' => 0, 'msg' => '提交失败：' . $e->getMessage()]);
                }
                
                $error = '提交失败：' . $e->getMessage();
            }
        }
        
        // 获取订单列表
        $orders = Db::name('scanwork_order')
            ->order('createtime desc')
            ->select();
            
        $this->view->assign([
            'orders' => $orders,
            'error' => $error,
            'success' => $success
        ]);
        
        return $this->view->fetch();
    }

    /**
     * 获取订单下的产品
     */
    public function getOrderProducts()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $orderId = $this->request->get('order_id');
        if (!$orderId) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        
        $products = Db::name('scanwork_order_model')
            ->alias('om')
            ->join('scanwork_model m', 'om.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->where('om.order_id', $orderId)
            ->field('p.id as product_id, p.name as product_name')
            ->group('p.id')
            ->select();
            
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $products]);
    }

    /**
     * 获取产品下的型号和工序
     */
    public function getProductModels()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $orderId = $this->request->get('order_id');
        $productId = $this->request->get('product_id');
        if (!$orderId || !$productId) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        
        // 获取该产品下的型号
        $models = Db::name('scanwork_order_model')
            ->alias('om')
            ->join('scanwork_model m', 'om.model_id = m.id')
            ->where('om.order_id', $orderId)
            ->where('m.product_id', $productId)
            ->field('om.model_id, m.name as model_name, om.quantity as order_quantity')
            ->select();
            
        // 获取所有工序
        $processes = Db::name('scanwork_process')
            ->where('status', 1)
            ->order('name')
            ->select();
            
        $result = [];
        foreach ($models as $model) {
            foreach ($processes as $process) {
                // 检查是否有该型号和工序的工价设置
                $processPrice = Db::name('scanwork_process_price')->where([
                    'model_id' => $model['model_id'],
                    'process_id' => $process['id']
                ])->find();
                
                if ($processPrice) {
                    $result[] = [
                        'model_id' => $model['model_id'],
                        'model_name' => $model['model_name'],
                        'process_id' => $process['id'],
                        'process_name' => $process['name'],
                        'order_quantity' => $model['order_quantity'],
                        'piece_price' => $processPrice['price'],
                        'time_price' => $processPrice['time_price'],
                        'display_name' => $model['model_name'] . ' (' . $process['name'] . ')'
                    ];
                }
            }
        }
            
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);
    }

    /**
     * 获取型号信息
     */
    public function getModelInfo()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $modelId = $this->request->get('model_id');
        if (!$modelId) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        
        $model = Db::name('scanwork_model')
            ->alias('m')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->where('m.id', $modelId)
            ->field('m.id, m.name as model_name, p.name as product_name')
            ->find();
            
        if (!$model) {
            return json(['code' => 0, 'msg' => '型号不存在']);
        }
        
        // 获取工价信息
        $prices = Db::name('scanwork_process_price')
            ->where('model_id', $modelId)
            ->select();
            
        $piecePrice = 0;
        $timePrice = 0;
        
        foreach ($prices as $price) {
            $piecePrice += $price['price'];
            $timePrice += $price['time_price'];
        }
        
        $model['piece_price'] = $piecePrice;
        $model['time_price'] = $timePrice;
        
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $model]);
    }

    /**
     * 获取订单下的产品型号
     */
    public function getOrderModels()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $orderId = $this->request->get('order_id');
        if (!$orderId) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        
        $orderModels = Db::name('scanwork_order_model')
            ->alias('om')
            ->join('scanwork_model m', 'om.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->where('om.order_id', $orderId)
            ->field('om.*, m.name as model_name, p.name as product_name')
            ->select();
            
        $result = [];
        foreach ($orderModels as $orderModel) {
            $result[] = [
                'model_id' => $orderModel['model_id'],
                'model_name' => $orderModel['model_name'],
                'product_name' => $orderModel['product_name'],
                'quantity' => $orderModel['quantity'],
                'display_name' => $orderModel['product_name'] . ' - ' . $orderModel['model_name']
            ];
        }
        
        // 明确返回JSON格式，避免框架自动处理导致的类型错误
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);
    }

    /**
     * 获取产品型号的工价信息
     */
    public function getModelPrices()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $modelId = $this->request->get('model_id');
        if (!$modelId) {
            $this->error('参数错误');
        }
        
        $prices = Db::name('scanwork_process_price')
            ->alias('pp')
            ->join('scanwork_process p', 'pp.process_id = p.id')
            ->where('pp.model_id', $modelId)
            ->field('pp.*, p.name as process_name')
            ->select();
            
        $this->success('获取成功', $prices);
    }

    /**
     * 我的主动报工记录
     */
    public function records()
    {
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        
        $workerId = $this->auth->id;
        
        $records = Db::name('scanwork_active_report')
            ->alias('ar')
            ->join('scanwork_order o', 'ar.order_id = o.id')
            ->join('scanwork_model m', 'ar.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->where('ar.user_id', $workerId)
            ->field('ar.*, o.order_no, p.name as product_name, m.name as model_name')
            ->order('ar.createtime desc')
            ->select();
            
        $this->view->assign('records', $records);
        return $this->view->fetch();
    }

    /**
     * 查看报工详情
     */
    public function detail()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $id = $this->request->get('id');
        $workerId = $this->auth->id;
        
        if (!$id) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        
        // 获取报工详情
        $activeReport = Db::name('scanwork_active_report')
            ->alias('ar')
            ->join('scanwork_order o', 'ar.order_id = o.id')
            ->join('scanwork_model m', 'ar.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'ar.process_id = pr.id')
            ->where('ar.id', $id)
            ->where('ar.user_id', $workerId)
            ->field('ar.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->find();
            
        if (!$activeReport) {
            return json(['code' => 0, 'msg' => '报工记录不存在']);
        }
        
        // 获取员工上传的图片
        $workerImages = Db::name('scanwork_active_report_image')
            ->where('active_report_id', $id)
            ->where('image_type', 1)
            ->select();
            
        // 获取管理员验货图片
        $auditImages = Db::name('scanwork_active_report_image')
            ->where('active_report_id', $id)
            ->where('image_type', 2)
            ->select();
            
        // 获取审核人信息
        $auditUser = null;
        if ($activeReport['audit_user_id']) {
            $auditUser = Db::name('user')
                ->where('id', $activeReport['audit_user_id'])
                ->field('nickname')
                ->find();
        }
        
        // 构建详情HTML
        $html = $this->buildDetailHtml($activeReport, $workerImages, $auditImages, $auditUser);
        
        return json(['code' => 1, 'msg' => '获取成功', 'data' => $html]);
    }

    /**
     * 删除报工记录
     */
    public function delete()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        $id = $this->request->post('id');
        $workerId = $this->auth->id;
        
        if (!$id) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        
        // 检查记录是否存在且属于当前用户
        $activeReport = Db::name('scanwork_active_report')
            ->where('id', $id)
            ->where('user_id', $workerId)
            ->where('status', 0) // 只能删除待审核的记录
            ->find();
            
        if (!$activeReport) {
            return json(['code' => 0, 'msg' => '记录不存在或无法删除']);
        }
        
        try {
            Db::startTrans();
            
            // 删除图片
            $images = Db::name('scanwork_active_report_image')
                ->where('active_report_id', $id)
                ->select();
                
            foreach ($images as $image) {
                $filePath = ROOT_PATH . 'public' . $image['image_url'];
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }
            
            Db::name('scanwork_active_report_image')
                ->where('active_report_id', $id)
                ->delete();
                
            // 删除报工记录
            Db::name('scanwork_active_report')
                ->where('id', $id)
                ->delete();
                
            Db::commit();
            return json(['code' => 1, 'msg' => '删除成功']);
            
        } catch (Exception $e) {
            Db::rollback();
            return json(['code' => 0, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 构建详情HTML
     */
    private function buildDetailHtml($activeReport, $workerImages, $auditImages, $auditUser)
    {
        $statusText = '';
        $statusClass = '';
        switch ($activeReport['status']) {
            case 0:
                $statusText = '待审核';
                $statusClass = 'bg-yellow-100 text-yellow-800';
                break;
            case 1:
                $statusText = '已通过';
                $statusClass = 'bg-green-100 text-green-800';
                break;
            case 2:
                $statusText = '已拒绝';
                $statusClass = 'bg-red-100 text-red-800';
                break;
        }
        
        $html = '
        <div class="space-y-6">
            <!-- 基本信息 -->
            <div class="bg-gray-50 p-4 rounded-lg">
                <h4 class="font-bold text-lg mb-3">基本信息</h4>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <span class="font-semibold">订单号：</span>
                        <span>' . $activeReport['order_no'] . '</span>
                    </div>
                    <div>
                        <span class="font-semibold">工作日期：</span>
                        <span>' . $activeReport['work_date'] . '</span>
                    </div>
                    <div>
                        <span class="font-semibold">产品：</span>
                        <span>' . $activeReport['product_name'] . '</span>
                    </div>
                    <div>
                        <span class="font-semibold">型号：</span>
                        <span>' . $activeReport['model_name'] . '</span>
                    </div>
                    <div>
                        <span class="font-semibold">工序：</span>
                        <span>' . $activeReport['process_name'] . '</span>
                    </div>
                    <div>
                        <span class="font-semibold">状态：</span>
                        <span class="px-2 py-1 text-xs font-semibold rounded-full ' . $statusClass . '">' . $statusText . '</span>
                    </div>
                </div>
            </div>
            
            <!-- 生产信息 -->
            <div class="bg-gray-50 p-4 rounded-lg">
                <h4 class="font-bold text-lg mb-3">生产信息</h4>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <span class="font-semibold">生产数量：</span>
                        <span>' . $activeReport['quantity'] . ' 件</span>
                    </div>
                    <div>
                        <span class="font-semibold">工作时长：</span>
                        <span>' . $activeReport['work_hours'] . ' 小时</span>
                    </div>
                    <div>
                        <span class="font-semibold">开始时间：</span>
                        <span>' . ($activeReport['start_time'] ?: '未填写') . '</span>
                    </div>
                    <div>
                        <span class="font-semibold">结束时间：</span>
                        <span>' . ($activeReport['end_time'] ?: '未填写') . '</span>
                    </div>
                </div>
            </div>
            
            <!-- 工资信息 -->
            <div class="bg-gray-50 p-4 rounded-lg">
                <h4 class="font-bold text-lg mb-3">工资信息</h4>
                <div class="grid grid-cols-3 gap-4">
                    <div>
                        <span class="font-semibold">计件工资：</span>
                        <span class="text-lg font-bold text-blue-600">￥' . number_format($activeReport['piece_wage'], 2) . '</span>
                    </div>
                    <div>
                        <span class="font-semibold">计时工资：</span>
                        <span class="text-lg font-bold text-blue-600">￥' . number_format($activeReport['time_wage'], 2) . '</span>
                    </div>
                    <div>
                        <span class="font-semibold">总工资：</span>
                        <span class="text-lg font-bold text-green-600">￥' . number_format($activeReport['total_wage'], 2) . '</span>
                    </div>
                </div>
            </div>';
            
        // 审核信息
        if ($activeReport['status'] != 0) {
            $html .= '
            <div class="bg-gray-50 p-4 rounded-lg">
                <h4 class="font-bold text-lg mb-3">审核信息</h4>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <span class="font-semibold">审核人：</span>
                        <span>' . ($auditUser ? $auditUser['nickname'] : '未知') . '</span>
                    </div>
                    <div>
                        <span class="font-semibold">审核时间：</span>
                        <span>' . date('Y-m-d H:i:s', $activeReport['audit_time']) . '</span>
                    </div>';
                    
            if ($activeReport['audit_reason']) {
                $html .= '
                    <div class="col-span-2">
                        <span class="font-semibold">审核意见：</span>
                        <span>' . $activeReport['audit_reason'] . '</span>
                    </div>';
            }
            
            $html .= '</div></div>';
        }
        
        // 备注信息
        if ($activeReport['remark']) {
            $html .= '
            <div class="bg-gray-50 p-4 rounded-lg">
                <h4 class="font-bold text-lg mb-3">备注信息</h4>
                <p>' . nl2br(htmlspecialchars($activeReport['remark'])) . '</p>
            </div>';
        }
        
        // 员工上传的图片
        if (!empty($workerImages)) {
            $html .= '
            <div class="bg-gray-50 p-4 rounded-lg">
                <h4 class="font-bold text-lg mb-3">完工图片</h4>
                <div class="grid grid-cols-3 gap-2">';
                
            foreach ($workerImages as $image) {
                $html .= '
                <div class="relative">
                    <img src="' . $image['image_url'] . '" class="w-full h-24 object-cover rounded cursor-pointer" onclick="previewImage(this.src)">
                </div>';
            }
            
            $html .= '</div></div>';
        }
        
        // 管理员验货图片
        if (!empty($auditImages)) {
            $html .= '
            <div class="bg-gray-50 p-4 rounded-lg">
                <h4 class="font-bold text-lg mb-3">验货图片</h4>
                <div class="grid grid-cols-3 gap-2">';
                
            foreach ($auditImages as $image) {
                $html .= '
                <div class="relative">
                    <img src="' . $image['image_url'] . '" class="w-full h-24 object-cover rounded cursor-pointer" onclick="previewImage(this.src)">
                </div>';
            }
            
            $html .= '</div></div>';
        }
        
        $html .= '</div>';
        
        return $html;
    }
}
